package com.yxe.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxe.pojo.User;
import com.yxe.service.UserService;
import com.yxe.mapper.UserMapper;
import com.yxe.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author X
 * @description 针对表【tb_user】的数据库操作Service实现
 * @createDate 2022-12-10 11:48:37
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AliSmsUtil aliSmsUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Value("${redis.expire.authCode}")
    private Long REDIS_EXPIRE_AUTH_CODE;
    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    @Override
    public Boolean generateLoginAuthCode(String telephone) {
        //验证手机号格式 或 号码是否正确
        boolean checkPhone = MobileUtil.checkPhone(telephone);
        if (checkPhone) {
            String authCode = RandomUtil.randomNumbers(6);
            if (aliSmsUtil.sendSms(telephone, authCode)) {
                //发送成功,在redis中存一份，并设置过期时间
                redisUtil.set(telephone, authCode, REDIS_EXPIRE_AUTH_CODE);
                return true;
            }
            return false;
        }
        return false;
    }

    @Override
    public SaTokenInfo loginByAuthCode(String telephone, String authCode) {
        //判断手机号是否正确
        if (!MobileUtil.checkPhone(telephone)) {
            return null;
        }

        //判断redis中是否有这个key，不判断的话如果没有该key会报空指针异常
        //判断验证码是否过期
        if (!redisUtil.hasKey(telephone)) {
            return null;
        }

        //判断验证码输入是否正确
        if (!authCode.equals(redisUtil.get(telephone).toString())) {
            return null;
        }

        //判断是否为新用户
        User user = findUserByTelephone(telephone);
        if (user == null) {
            //新用户插入MySQL
            User insertUser = new User();
            insertUser.setTelephone(telephone);
            insertUser.setNickname("用户" + RandomUtil.randomString(12));
            //新用户设置默认头像
            insertUser.setHeadPortrait("https://baiyang425.oss-cn-hangzhou.aliyuncs.com/images//572b007ea100499ab9951ce3df5870d7-1.png");
            userMapper.insert(insertUser);
        }

        //密码校验成功后重新查询userId并登录，一行代码实现登录
        StpUtil.login(findUserByTelephone(telephone).getUserId());
        //获取当前登录用户Token信息
        return StpUtil.getTokenInfo();
    }

    @Override
    public User findUserByTelephone(String telephone) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("telephone", telephone));
    }

    @Override
    public SaTokenInfo loginByPwd(String telephone, String password) {
        boolean checkPhone = MobileUtil.checkPhone(telephone);
        if (checkPhone) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("telephone", telephone);
            queryWrapper.eq("password", password);
            User user = userMapper.selectOne(queryWrapper);
            if (user != null) {
                // 密码校验成功后登录，一行代码实现登录
                StpUtil.login(user.getUserId());
                // 获取当前登录用户Token信息
                return StpUtil.getTokenInfo();
            }
        }
        return null;
    }

    @Override
    public Boolean updatePasswordById(String authCode, String newPassword) {
        //获取当前登录用户id
        int userId = StpUtil.getLoginIdAsInt();
        String telephone = userMapper.selectById(userId).getTelephone();

        //判断用户输入的验证码是否正确
        if(!authCode.equals(redisUtil.get(telephone).toString())){
            return false;
        }

        //验证码正确，修改数据库密码
        User user = new User();
        user.setUserId(userId);
        user.setPassword(newPassword);
        userMapper.updateById(user);
        return true;
    }

    @Override
    public void uploadHeadPortrait(MultipartFile multipartFile) {
        //获取当前登录的用户id
        int userId = StpUtil.getLoginIdAsInt();
        try {
            File file = MultipartFileToFileUtil.multipartFileToFile(multipartFile);
            String fileName = aliyunOssUtil.upload(file);
            String fileUrl = "https://baiyang425.oss-cn-hangzhou.aliyuncs.com/".concat(fileName);

            //上传成功后，根据用户id更改头像地址
            User user = new User();
            user.setUserId(userId);
            user.setHeadPortrait(fileUrl);
            userMapper.updateById(user);

            //数据库更新完成后，删除MultiFile转File在本地生成临时文件（防止占用内存）
            MultipartFileToFileUtil.deleteTempFile(file);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Boolean generateUpdateAuthCode() {
        int loginUserId = StpUtil.getLoginIdAsInt();
        String telephone = userMapper.selectById(loginUserId).getTelephone();
        String authCode = RandomUtil.randomNumbers(6);
        if (aliSmsUtil.sendSms(telephone, authCode)) {
            //发送成功,在redis中存一份，并设置过期时间
            redisUtil.set(telephone, authCode, REDIS_EXPIRE_AUTH_CODE);
            return true;
        }
        return false;
    }

    /**
     * 修改用户昵称
     *
     * @param nickname 昵称
     * @return 影响行数
     */
    @Override
    public Integer updateNickName(String nickname) {
        int userId = StpUtil.getLoginIdAsInt();
        User user = new User();
        user.setUserId(userId);
        user.setNickname(nickname);
        return userMapper.updateById(user);
    }

    /*@Autowired
    private JwtUtil jwtUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;*/

    /*@Override
    public String loginByPwd(String telephone, String password) {
        boolean checkPhone = MobileUtil.checkPhone(telephone);
        if (checkPhone) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("telephone", telephone);
            queryWrapper.eq("password", password);
            User user = userMapper.selectOne(queryWrapper);
            if (user != null) {
                HashMap<String, String> map = new HashMap<>();
                map.put("userId", user.getUserId().toString());
                map.put("telephone", telephone);
                return jwtUtil.createJwt(map);
            }
        }
        return null;
    }*/

    /*@Override
    public Map<String, String> getAdminInfo(String fullToken) {
        String token = fullToken.replace(tokenHead, "");
        System.out.println("token = " + token);
        Map<String, Claim> claims = jwtUtil.getClaimsFromToken(token);
        String userId = claims.get("userId").asString();
        String telephone = claims.get("telephone").asString();

        System.out.println("userId = " + userId);
        System.out.println("telephone = " + telephone);

        //将得到的用户id和用户手机号结果封装到map集合中
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("telephone", telephone);

        return map;
    }*/
}




